package com.qg.service.user_login;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.qg.utils.Constants;
import com.qg.module.pojo.QgUser;
import com.qg.service.QgUserService;
import com.qg.utils.*;

import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class LoginQgUserImpl implements LoginQgUser{

    @Reference
    private QgUserService qgUserService;
    @Resource
    private RedisUtil redisUtil;
    /**
     * 根据号码和密码查询用户
     * @param phone
     * @param password
     * @return
     * @throws Exception
     */
    @Override
    public QgUser queryUser_PhoneAndPassword(String phone, String password) throws Exception {
        Map<String,Object> userMap=new HashMap<String,Object>();
        userMap.put("phone",phone);
        userMap.put("password",password);
        QgUser qgUser=qgUserService.getQgUserListByMap(userMap).get(0);
        return qgUser;
    }


    /**
     * 创建微信token
     * @param userInfoJsonstr
     * @return
     * @throws Exception
     */
    @Override
    public String createWxUserToken(String userInfoJsonstr) throws Exception {
        JSONObject userInfoJson=JSONObject.parseObject(userInfoJsonstr);
        String openId=userInfoJson.getString("openid");
        Map<String,Object> param=new HashMap<String,Object>();
        List<QgUser> qgUserList=qgUserService.getQgUserListByMap(param);
        QgUser qgUser=null;
        //如果不在库中，说明用户首次进行微信登录
        if(EmptyUtils.isEmpty(qgUserList)){
            qgUser=new QgUser();
            qgUser.setId(IdWorker.getId());
            qgUser.setCreatedTime(new Date());
            qgUser.setRealName(userInfoJson.getString("nickname"));
            qgUser.setUpdatedTime(new Date());
            qgUser.setWxUserId(openId);
            qgUserService.qdtxAddQgUser(qgUser);
        }else{
            qgUser=qgUserList.get(0);
        }
        //为用户执行自动登录的操作
        String token= Constants.tokenPrefix+ TokenUtils.createToken(qgUser.getId(),qgUser.getWxUserId());
        redisUtil.setStr(token, JSONObject.toJSONString(qgUser), new Long(Constants.TOKEN_TIMEOUT));
        redisUtil.setStr(qgUser.getId(), token,new Long(Constants.TOKEN_TIMEOUT));
        return token;
    }
}
